package com.webdemo.service.muliti.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webdemo.dal.dao.one.UserMapper;
import com.webdemo.dal.dao.other.MulitiDbMapper;
import com.webdemo.dal.model.Db2Table;
import com.webdemo.dal.model.Users;
import com.webdemo.service.muliti.MulitiService;
import com.webdemo.util.mulitichange.DbChangeContextHolder;

@Service
public class MulitiServiceImpl implements MulitiService {

	@Autowired
	private MulitiDbMapper mulitiDbMapper;
	
	@Autowired
	private UserMapper userDbMapper;
	
	@Override
	public Db2Table sb(Integer id) {
		return mulitiDbMapper.sb(id);
	}

	@Override
	public int insert(Db2Table ta) {
		return mulitiDbMapper.insert(ta);
	}
	
	//测试同一个库事务
	@Override
	public void insertOneDbTranc(){
		Users user = new Users();
		user.setUserId(0);
		user.setUsername("test1_两次插入事务");
		user.setPassword("test1_两次插入事务");
		userDbMapper.insert(user);
		//int t = 1/0;
		Users user1 = new Users();
		user1.setUserId(0);
		user1.setUsername("test1_两次插入事务");
		user1.setPassword("test1_两次插入事务");
		userDbMapper.insert(user1);
	}

	//测试跨两个库事务
	@Override
	public void insertMulitiTranc(){
		Users user = new Users();
		user.setUserId(0);
		user.setUsername("测试第一个库事务!");
		user.setPassword("测试第一个库事务!");
		userDbMapper.insert(user);
		Db2Table db2 = new Db2Table();
		db2.setId(2);
		db2.setDesc1("测试第二个库事务!");
		mulitiDbMapper.insert(db2);
		int m = 1/0;
	}
	
	//测试切换两个库
	@Override
	public void insertMulitiChangeTranc(){
		Users user = new Users();
		user.setUserId(0);
		user.setUsername("测试第一个库事务change!");
		user.setPassword("测试第一个库事务change!");
		DbChangeContextHolder.setDbChange("dataSrcKey");
		userDbMapper.insert(user);
		Db2Table db2 = new Db2Table();
		db2.setId(2);
		db2.setDesc1("测试第二个库事务change!");
		DbChangeContextHolder.setDbChange("dataSrc1Key");
		mulitiDbMapper.insert(db2);
	}
}
